<?php
namespace addons\xilujob\controller;

use addons\xilujob\library\Config;
use app\common\model\xilujob\PackageOrder;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Http\StreamResponse;
use think\Controller;
use think\Db;
use think\Exception;
use think\exception\ThrowableError;
use think\Log;

class WeixinPublic extends Controller
{
    protected $app;
    protected $payment;

    public function _initialize()
    {
        parent::_initialize();

        //$this->app = Factory::miniProgram(Config::load());

        $pay_config = get_addon_config('xilujob');
        $payment_config = [
            // 必要配置
            'app_id'             => $pay_config['mp_app_id'] ?? '',
            'mch_id'             => $pay_config['mch_id'] ?? '',
            'key'                => $pay_config['mch_key'] ?? '',   // API 密钥
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => $pay_config['apiclient_cert'] ?? '', // XXX: 绝对路径！！！！
            'key_path'           => $pay_config['apiclient_key'] ?? '',      // XXX: 绝对路径！！！！
            'notify_url'         => '',     // 你也可以在下单时单独设置来想覆盖它
        ];
        $this->payment = Factory::payment($payment_config);

    }

    /**
     * 生成统一订单
     */
    public function union_order($order){

        $orderinfo = [
            'body'              => $order['body'],
            'out_trade_no'      => $order['order_no'],
            'total_fee'         => (int)($order['pay_price'] * 100),
            //'spbill_create_ip'  => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url'        => $order['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type'        => $order['trade_type'], // 请对应换成你的支付方式对应的值类型
        ];
        if($order['trade_type'] == 'JSAPI'){
            $orderinfo['openid'] = $order['openid'];
        }
        try {
            $wxpay = $this->payment->order->unify($orderinfo);
            if($wxpay['return_code'] !== 'SUCCESS' && $wxpay['result_code'] !== 'SUCCESS'){
                throw new Exception($wxpay['err_code_des']);
            }
            if($orderinfo['trade_type'] == "JSAPI"){
                return $this->payment->jssdk->bridgeConfig($wxpay['prepay_id'], false);
            }
            return $wxpay;
        }catch (Exception $e){
            throw $e;
        }
    }


    /**
     * 支付回调
     */
    public function notify()
    {
//        Log::record(file_get_contents('php://input'), "notify");
        $response = $this->payment->handlePaidNotify(function ($message, $fail){
            // 你的逻辑
            Log::record($message, "debug");
            $order_no = $message['out_trade_no'];
            $trade_no = $message['transaction_id'];
            Db::startTrans();
            try {
                PackageOrder::pay_notify($order_no,$trade_no);
            }catch (Exception $e){
                Db::rollback();;
                return $e->getMessage();
            }
            Db::commit();
        });

        $response->send();
        return;
    }

}